package xingxing

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
	"time"
)

const wxcheckdomainurl = "http://vip.xxweixin.com/weixin/wx_domain.php"

type Client struct {
	User string `json:"user"`
	Key  string `json:"key"`
}

func (c *Client) WxCheckDomain(domain string) (res WxCheckDomainResponse, err error) {
	form := url.Values{}
	form.Set("user", c.User)
	form.Set("domain", domain)
	form.Set("key", c.Key)
	resp, err := request("POST", fmt.Sprintf("%v?%v", wxcheckdomainurl, form.Encode()), nil, nil)
	if err != nil {
		return res, err
	}
	err = json.Unmarshal(resp, &res)
	if err != nil {
		return res, err
	}
	return res, nil
}

func request(method string, url string, headers map[string]string, body io.Reader) (res []byte, err error) {
	method = strings.ToUpper(method)
	request, err := http.NewRequest(method, url, body)
	if err != nil {
		return nil, err
	}
	for k, v := range headers {
		request.Header.Set(k, v)
	}
	client := http.Client{
		Timeout: time.Second * 15,
	}
	resp, err := client.Do(request)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return respBytes, nil
}
